from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings  # 为QQ对象提取配置文件中的属性内容
from rest_framework.generics import CreateAPIView
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

# Create your views here.


#     一.构建跳转链接
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializer


class QQLoginURLView(APIView):
        # 1.生成QQ对象
        # 获取前端数据
        def get(self, request):
            state = request.query_params.get('next')
            if state is None:
                state = '/'
            # 1、生成qq对象
            qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                         redirect_uri=settings.QQ_REDIRECT_URI, state=state)

             # 2.调用生成url的方法
            login_url=qq.get_qq_url()

            # 3.返回url
            return Response({"login_url":login_url})

#     二.获取openid 和绑定openid
class OauthView(CreateAPIView):

    # 指定使用的序列化器
    serializer_class = OauthSerializer
    def get(self, request):
        # 1.获取前端传递的code值 查询字符串的形式获取
        code = request.query_params.get("code")
        if code is None:
            return Response({"errors":"缺少code值"},status=400)

        # 2.通过code值请求QQ服务器获取access_token值
        # 01.先实例化一个对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state="/")
        # 02.通过实例化对象再加上QQ提供的方法获取code值
        access_token = qq.get_access_token(code)
        # 3.通过access_token值请求QQ服务器获取openid值
        openid = qq.get_open_id(access_token)

        # 4.判断openid和美多用户是否绑定
        # 通过try捕获异常返回给前端
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 5.如果未绑定,就绑定openid
            # 生成TJF对象
            tjs = TJS(settings.SECRET_KEY, 300)
            # 加密
            data = tjs.dumps({'openid': openid}).decode()
            # 将加密后的openid返回给前端
            return Response({"access_token":data})
        # 6.如果绑定过则直接登陆
        # else表示没有异常捕获到的化执行...下面代码
        else:
            # 获取用户对象
            user = qq_user.user

            # 生成jwt token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })


